package com.moji.service.impl;

import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.moji.common.entity.MyPage;
import com.moji.common.utils.PageUtil;
import com.moji.entity.MjOrder;
import com.moji.entity.MjWorkOrder;
import com.moji.entity.MjWorkOrderDetail;
import com.moji.entity.SysMessage;
import com.moji.entity.dto.QueryWorkOrderDto;
import com.moji.entity.vo.MjWorkOrderVo;
import com.moji.mapper.MjWorkOrderMapper;
import com.moji.service.MjWorkOrderDetailService;
import com.moji.service.MjWorkOrderService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.moji.service.SysMessageService;
import com.moji.util.DateUtils;
import com.moji.util.IdGenerator;
import com.moji.util.MoJiCommonUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 电子工单表 服务实现类
 * </p>
 *
 * @author ccl
 * @since 2024-08-16
 */
@Service
public class MjWorkOrderServiceImpl extends ServiceImpl<MjWorkOrderMapper, MjWorkOrder> implements MjWorkOrderService {

    @Resource
    private SysMessageService sysMessageService;

    @Resource
    private MjWorkOrderDetailService mjWorkOrderDetailService;

    @Resource
    private IdGenerator idGenerator;

    @Override
    public MyPage<MjWorkOrder> queryByPage(QueryWorkOrderDto dto) {
        LambdaQueryWrapper<MjWorkOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(ObjectUtil.isNotEmpty(dto.getWorkName()),MjWorkOrder::getWorkName,dto.getWorkName());
        wrapper.eq(ObjectUtil.isNotEmpty(dto.getWorkType()),MjWorkOrder::getWorkType,dto.getWorkType());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getMobile()),MjWorkOrder::getMobile,dto.getMobile());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getUserName()),MjWorkOrder::getUserName,dto.getUserName());
        wrapper.like(ObjectUtil.isNotEmpty(dto.getStatus()),MjWorkOrder::getStatus,dto.getStatus());
        wrapper.orderByDesc(MjWorkOrder::getCreateTime);
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<MjWorkOrder> mjWorkOrderList = list(wrapper);
        PageInfo<MjWorkOrder> info = new PageInfo<>(mjWorkOrderList);
        return PageUtil.PageInfo2MyPage(info);
    }

    @Override
    public boolean delete(Long id) {
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("主键ID不能为空,请核查!");
        }
        return this.removeById(id);
    }

    @Override
    public boolean add(MjWorkOrder mjWorkOrder) {
        String workCode= idGenerator.idGenerator("DZGD");
        mjWorkOrder.setWorkCode(workCode);
        mjWorkOrder.setStatus(0);
        mjWorkOrder.setUserCode(MoJiCommonUtils.getUserCode());
        mjWorkOrder.setCreateId(MoJiCommonUtils.getUserCode());
        mjWorkOrder.setUpdateId(MoJiCommonUtils.getUserCode());
        mjWorkOrder.setCreateTime(new Date());
        mjWorkOrder.setUpdateTime(new Date());
        return this.save(mjWorkOrder);
    }

    @Override
    public boolean edit(MjWorkOrder mjWorkOrder) {
        MjWorkOrder mjWorkOrder1=this.getById(mjWorkOrder.getId());
        BeanUtils.copyProperties(mjWorkOrder,mjWorkOrder1);
        mjWorkOrder1.setUpdateId(MoJiCommonUtils.getUserCode());
        mjWorkOrder1.setUpdateTime(new Date());
        return this.updateById(mjWorkOrder1);
    }

    @Override
    public MjWorkOrderVo detail(Long id) {
        MjWorkOrder mjWorkOrder=this.getById(id);
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("工单数据不存在,请核查!");
        }
        MjWorkOrderVo mjWorkOrderVo=new MjWorkOrderVo();
        BeanUtils.copyProperties(mjWorkOrder,mjWorkOrderVo);

        List<MjWorkOrderDetail> workOrderDetails=mjWorkOrderDetailService.list(new LambdaQueryWrapper<MjWorkOrderDetail>()
                .eq(MjWorkOrderDetail::getWorkCode,mjWorkOrder.getWorkCode()));
        mjWorkOrderVo.setWorkOrderDetails(workOrderDetails);
        return mjWorkOrderVo;
    }

    @Override
    public boolean complete(Long id) {
        MjWorkOrder mjWorkOrder=this.getById(id);
        if(ObjectUtil.isEmpty(id)){
            throw new RuntimeException("工单数据不存在,请核查!");
        }
        mjWorkOrder.setStatus(2);
        return this.updateById(mjWorkOrder);
    }

    @Override
    public void completeWork() {
        LambdaQueryWrapper<MjWorkOrder> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(MjWorkOrder::getStatus,1);
        List<MjWorkOrder> mjWorkOrderList = this.list(wrapper);
        if(ObjectUtil.isNotEmpty(mjWorkOrderList)){
            mjWorkOrderList.forEach(mjWorkOrder -> {
                LambdaQueryWrapper<MjWorkOrderDetail> wrapperDetail = new LambdaQueryWrapper<>();
                wrapperDetail.eq(MjWorkOrderDetail::getWorkCode,mjWorkOrder.getWorkCode());
                wrapperDetail.orderByDesc(MjWorkOrderDetail::getCreateTime);
                wrapperDetail.last("limit 1");
                MjWorkOrderDetail mjWorkOrderDetail=mjWorkOrderDetailService.getOne(wrapperDetail);
                if(mjWorkOrderDetail !=null){
                    long diff=DateUtil.between(new Date(),mjWorkOrderDetail.getCreateTime(),DateUnit.MINUTE);
                    System.out.println("时间差值=========="+diff);
                    MjWorkOrder workOrder=this.getOne(new LambdaQueryWrapper<MjWorkOrder>()
                            .eq(MjWorkOrder::getWorkCode,mjWorkOrderDetail.getWorkCode()));
                    if(diff ==8){
                        System.out.println("工单完结消息提醒-==============");
                        //增加消息通知
                        SysMessage sysMessage=new SysMessage();
                        sysMessage.setReceiveUserId(workOrder.getUserCode());
                        sysMessage.setSendUserId(mjWorkOrderDetail.getCreateId());
                        sysMessage.setMarkAsRead(0);
                        sysMessage.setMessageTitle("工单完结");
                        //消息类型 1-发票提醒 2-下单成功 3-待支付提醒4-超时未支付 5-工单回复 6-工单完结 7-服务到期提醒
                        sysMessage.setMessageType("6");
                        LocalDateTime currentTime=LocalDateTime.now();
                        LocalDateTime newtTime=currentTime.minusMinutes(2);

                        sysMessage.setMessageCenter("尊敬的用户您好：您于"+ DateUtils.formatDate(mjWorkOrderDetail.getCreateTime(),DateUtils.DATE_FORMAT_EXP1) +"提交的工单已由工作人员进行回复，" +
                                "工单编号为："+mjWorkOrderDetail.getWorkCode()+"，将在2分钟后完结！");
                        sysMessage.setBillNo(mjWorkOrderDetail.getId()+"");
                        sysMessage.setBillTypeCode("0");
                        sysMessage.setCreateId(mjWorkOrderDetail.getCreateId());
                        sysMessage.setUpdateId(mjWorkOrderDetail.getCreateId());
                        sysMessage.setCreateTime(new Date());
                        sysMessage.setUpdateTime(new Date());
                        sysMessageService.save(sysMessage);

                    }
                    if(diff ==10){
                        System.out.println("工单完结执行-==============");
                        workOrder.setStatus(2);
                        this.updateById(workOrder);
                    }
                }
            });

        }
    }

}
